import { ref } from 'vue'
import { defineStore } from 'pinia'
import { routerApi } from '@/apis/system/menu.js'
import Layout from'@/layouts/index';
import NestView from'@/layouts/nestView/nestView.vue';
import router from '@/router';

const useRoutersStore = defineStore('router', () => {

  // 菜单信息
  const menus = ref([])
  // 获取菜单，保存路由信息
  const saveRouters = async()=>{
    const res = await routerApi();
    menus.value = res.data;
    buildRouter(JSON.parse(JSON.stringify(res.data))).forEach(item=>{
      router.addRoute(item)
    })
    router.addRoute({ path: '/:catchAll(.*)', redirect:'/404',hidden:true})
  };

  // 清除菜单信息
  const clearRouters = async()=>{
    menus.value = []; 
  };

  return {
    menus, saveRouters, clearRouters
  }
})


const buildRouter=(asyncRouterMap, lastRouter = false, type = false)=>{
    return asyncRouterMap.filter(route => {
        if (type && route.children) {
          route.children = filterChildren(route.children)
        }
        if (route.component) {
          if (route.component === 'Layout') {
            route.component = Layout
          } else if (route.component === 'NestView') {
            route.component = NestView
          } else {
            route.component = loadView(route.component)
          }
        }
        if (route.children != null && route.children && route.children.length) {
          route.children = buildRouter(route.children, route, type)
        } else {
          delete route['children']
          delete route['redirect']
        }
        return true
    })
}


const filterChildren=(childrenMap, lastRouter = false)=>{
    var children = []
    childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'NestView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

const loadView = (view) => {
  if (process.env.NODE_ENV === 'development') {
      return () => import(`../../views/${view}`)
      // return (resolve) => require([`@/views/${view}`], resolve)  // vite下require会报错，没解决！！！直接用生产了
  } else {
    // 使用 import 实现生产环境的路由懒加载
      return () => import(`@/views/${view}`)
  }
}

export default useRoutersStore